import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:love_app/common/su.dart';
import 'package:love_app/common/su_dialog.dart';
import 'package:love_app/config/app_color.dart';
import 'package:love_app/enum/send_message.dart';
import 'package:love_app/service/message_api.dart';
import 'package:love_app/service/register_api.dart';

class ForgetPassWord extends StatefulWidget {
  @override
  _ForgetPassWordState createState() => _ForgetPassWordState();
}

class _ForgetPassWordState extends State<ForgetPassWord> {
  TextEditingController _usernameController = TextEditingController(); // 用户名控制器
  TextEditingController _passwordController = TextEditingController(); // 密码控制器
  TextEditingController _phoneCodeController =
      TextEditingController(); // 验证码控制器
  FocusNode _usernameFocusNode = new FocusNode(); // 用户名框焦点
  FocusNode _passwordFocusNode = new FocusNode(); // 密码框焦点
  FocusNode _phoneCodeFocusNode = new FocusNode(); // 验证码控制器
  GlobalKey _fromKey = GlobalKey<FormState>(); // form表单key
  bool _usernameInputHasData = false; // 是否显示用户名框后面x
  bool _passwordInputHasShow = false; // 是否显示密码
  int _count = 60; // 循环周期， 一秒为一个周期， 循环60次
  String _yzmButtonText = '获取验证码'; // 获取验证码按钮
  Timer _timer; // 创建倒计时

  @override
  void initState() {
    super.initState();

    // 监听手机号码框
    _usernameController.addListener(() {
      setState(() {});
    });

    // 监听用户名框
    _passwordController.addListener(() {
      setState(() {});
    });

    // 监听验证码框
    _phoneCodeController.addListener(() {
      setState(() {});
    });
  }

  @override
  void dispose() {
    _count = 0;
    if (_timer != null) {
      // 如果有实例化就取消
      _timer.cancel();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Su().appBar(
        '重置密码',
      ),
      body: _body(),
    );
  }

  Widget _body() {
    return SingleChildScrollView(
      child: Container(
        margin: EdgeInsets.only(
          top: Su().h(106),
        ),
        child: Column(
          children: <Widget>[
            _registerInput(),
          ],
        ),
      ),
    );
  }

  // 注册表单
  Widget _registerInput() {
    return Container(
      child: Form(
        key: _fromKey,
        autovalidate: true,
        child: Column(
          children: <Widget>[
            _phoneInput(),
            _yzmInput(),
            _pwdInput(),
            _registerButton(),
            _ruleText(),
          ],
        ),
      ),
    );
  }

  // 手机号码输入框
  Widget _phoneInput() {
    return TextFormField(
      autofocus: true, // 自动对焦
      controller: _usernameController, // 控制器
      focusNode: _usernameFocusNode,
      keyboardType: TextInputType.phone, // 键盘样式
      cursorColor: ThemeColor, // 光标颜色
      inputFormatters: [LengthLimitingTextInputFormatter(11)],
      // 最大长度， 右下角字数消失
      decoration: InputDecoration(
        labelText: "手机号码",
        hintText: "请输入用手机号码",
        prefixText: '+86  ',
        filled: true,
        counterText: '', // 使用一个小技巧把提示文字弄没了
        fillColor: Color.fromRGBO(255, 255, 255, 1), // 提示字体样式
        labelStyle: Su().textStyle(ThemeColor, 35), // 提示字体样式
        prefixIcon: Icon(
          Icons.phone_android,
          color: ThemeColor,
        ), // 左边的icon
        suffixIcon: (_usernameInputHasData) // 最右边的icon
            ? IconButton(
                icon: Icon(
                  Icons.clear,
                  color: ThemeColor,
                ),
                onPressed: () {
                  _usernameController.clear();
                },
              )
            : null,
        // 选择的焦点下划线样式
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: ThemeColor),
        ),
        // 未选择焦点下划线样式
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(
            color: Color.fromRGBO(224, 224, 224, 1),
          ),
        ),
      ),
    );
  }

  // 获取验证码
  Widget _yzmInput() {
    return TextFormField(
      autofocus: true, // 自动对焦
      controller: _phoneCodeController,
      focusNode: _phoneCodeFocusNode,
      keyboardType: TextInputType.number,
      cursorColor: ThemeColor,
      inputFormatters: [LengthLimitingTextInputFormatter(6)],
      decoration: InputDecoration(
        labelText: "验证码",
        hintText: "请输入验证码",
        filled: true,
        fillColor: Color.fromRGBO(255, 255, 255, 1),
        labelStyle: Su().textStyle(ThemeColor, 35),
        prefixIcon: Icon(
          Icons.message,
          color: ThemeColor,
        ),
        // 选择的焦点下划线样式
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(
            color: ThemeColor,
          ),
        ),
        // 未选择焦点下划线样式
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(
            color: Color.fromRGBO(224, 224, 224, 1),
          ),
        ),
        suffixIcon: Padding(
          padding: EdgeInsets.only(right: ScreenUtil().setWidth(20.0)),
          child: RaisedButton(
            // 点击验证码按钮(null则不能点击)
            onPressed: _isPhone() == true ? null : _yzmBottonFun,
            // 按钮禁止时颜色
            disabledColor: Color.fromRGBO(233, 140, 166, 1),
            color: Color.fromRGBO(238, 127, 168, 1),
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            child: Text(
              _yzmButtonText,
              style: Su().textStyle(Colors.white, 24.0),
            ),
          ),
        ),
      ),
    );
  }

  // 获取验证码按钮实现方法
  void _yzmBottonFun() async {
    bool success = await MessgerApi()
        .sendMesage(_usernameController.text, SendMessageType.update);
    // 如果返回的类型为model类型，则成功
    if (success == true) {
      _sendMessageSuccess();
    }
  }

  // 验证码发送成功
  void _sendMessageSuccess() {
    // 定义一个循环， 周期为一秒一次
    final callback = (timer) {
      setState(() {
        if (_count < 1) {
          _yzmButtonText = "重新获取";
          _timer.cancel();
        } else {
          _count -= 1;
          _yzmButtonText = _count.toString() + "s";
        }
      });
    };
    // 周期性的倒计时(1秒一个周期)
    _timer = Timer.periodic(Duration(seconds: 1), callback);
  }

  // 密码框
  Widget _pwdInput() {
    return TextFormField(
      autofocus: true, // 自动对焦
      controller: _passwordController,
      focusNode: _passwordFocusNode,
      obscureText: !_passwordInputHasShow, // 是否隐藏
      cursorColor: ThemeColor,
      inputFormatters: [LengthLimitingTextInputFormatter(25)],
      // validator:(v){
      //     return v.trim().length > 5 ? null : '密码不能少于6位';
      //   },
      decoration: InputDecoration(
        labelText: "密码",
        hintText: "请输入登录密码",
        filled: true,
        fillColor: Color.fromRGBO(255, 255, 255, 1),
        labelStyle: Su().textStyle(ThemeColor, 35),
        prefixIcon: Icon(
          Icons.lock,
          color: ThemeColor,
        ),
        // 选择的焦点下划线样式
        focusedBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: ThemeColor),
        ),
        // 未选择焦点下划线样式
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(
            color: Color.fromRGBO(224, 224, 224, 1),
          ),
        ),
        suffixIcon: IconButton(
          icon: Icon(
            (_passwordInputHasShow) ? Icons.visibility : Icons.visibility_off,
            color: ThemeColor,
          ),
          onPressed: () {
            setState(() {
              _passwordInputHasShow = !_passwordInputHasShow;
            });
          },
        ),
      ),
    );
  }

  // 注册按钮
  Widget _registerButton() {
    return Container(
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(95.0)),
      child: InkWell(
        onTap: () {
          // 清除Filed焦点
          _usernameFocusNode.unfocus();
          _passwordFocusNode.unfocus();
          _phoneCodeFocusNode.unfocus();
          _registerFun();
        },
        child: Container(
          height: ScreenUtil().setHeight(80),
          width: ScreenUtil().setWidth(566),
          alignment: Alignment.center,
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(50.0),
              gradient: _registerButtonIsNoDispaly()
                  ? LinearGradient(
                      colors: [
                        Color.fromRGBO(238, 127, 168, 1),
                        Color.fromRGBO(237, 120, 127, 1),
                      ],
                    )
                  : LinearGradient(
                      colors: [
                        Color.fromRGBO(242, 187, 209, 1),
                        Color.fromRGBO(242, 183, 188, 1),
                      ],
                    )),
          child: Text(
            '重置密码',
            style: Su().textStyle(Colors.white, 36),
          ),
        ),
      ),
    );
  }

  // 满足注册按钮的条件
  bool _registerButtonIsNoDispaly({bool showError = false}) {
    int phoneTextLength = _usernameController.text.length; // 手机号码
    int yzmCodeLength = _phoneCodeController.text.length; // 验证码
    int passwordLength = _passwordController.text.length; // 密码

    if (phoneTextLength != 11) {
      _showInputError(showError, '手机号码错误');
      return false;
    }
    if (yzmCodeLength != 6) {
      _showInputError(showError, '验证码长度错误');
      return false;
    }
    if (passwordLength < 6 || passwordLength > 25) {
      _showInputError(showError, '密码必须6-25位');
      return false;
    }
    return true;
  }

  /// 判断手机号码是是否合法
  bool _isPhone() {
    int phoneTextLength = _usernameController.text.length; // 手机号码

    if (phoneTextLength == 11) {
      return false;
    }
    // _showInputError(true, '手机号码错误');
    return true;
  }

  // 显示输入框不合法提示
  void _showInputError(bool show, String msg) {
    if (show == true) {
      SuDialog.showToast(msg);
    }
  }

  // 条例
  Widget _ruleText() {
    return Container(
      margin: EdgeInsets.only(top: ScreenUtil().setHeight(22.0)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            '重置密码表示同意',
            style: TextStyle(fontSize: ScreenUtil().setSp(22.0)),
          ),
          Padding(
            padding: EdgeInsets.only(left: 2),
            child: InkWell(
              onTap: () {},
              child: Text(
                '隐私政策，服务条例',
                style: TextStyle(
                  color: Color.fromRGBO(238, 135, 176, 1),
                  fontSize: ScreenUtil().setSp(22.0),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 点击
  void _registerFun()async{
    if(_registerButtonIsNoDispaly(showError: true) == true){
      String phone = _usernameController.text;
      String phoneCode = _phoneCodeController.text;
      String password = _passwordController.text;
      bool isSuccess = await RegisterApi().forgetPassword(phone, phoneCode, password);
      if(isSuccess == true){
        SuDialog.showToast("重置成功");
        Navigator.pop(context);
      }else{
        SuDialog.showToast("重置失败");
      }
      _timer.cancel();
    }
  }
}
